#include"dic.hh"
#include<ctype.h>

using std::cout;
using std::endl;
using std::string;
using std::ifstream;
using std::ofstream;
using std::istringstream;

TextQuery::TextQuery()
    :_lines(std::make_shared<std::vector<std::string>>())
{}

void TextQuery::readFile(const string &filename) 
{
    _lines->reserve(10000);
    ifstream ifs(filename);
    if(!ifs)
    {
        std::cerr<<"file :"<<filename<<" open failed"<<endl;
        return ;
    }
    //开启了文件输入流

    string line;
    int linenum=0;
    while(std::getline(ifs,line))
    {
        //存储到行
        _lines->push_back(line);
        ++linenum;

        for(auto& i:line)
        {
            if(!isalpha(i))
            {
                i=' ';
            }
            else 
            {
                i=tolower(i);
            }
        }
        istringstream iss(line);
        string word;
        while(iss>>word)
        {
            if(word.size()==0)
            {
                continue;
            }
            //获取到每个单词，记录当前单词的行并且计数单词数量
            auto it= _word2Numbers.find(word);
            if(it ==_word2Numbers.end())
            {
                //初始化
                _word2Numbers[word]=std::make_shared<std::set<int>>();
                _word2Numbers[word]->insert(linenum);
            }
            else 
            {
                _word2Numbers[word]->insert(linenum);
            }
            cout<<word<<endl;
        }
    }
    ifs.close();
}
void TextQuery::query(const string& word)
{
    string record(word);

    for(auto&i:record)
    {
        i=tolower(i);
    }
    auto it=_word2Numbers.find(record);

    cout<<"-------------------------------------"<<endl;
    if(it==_word2Numbers.end())
    {
        cout<<"word "<<word<<" occurs "<<" 0 time"<<endl;
    cout<<"-------------------------------------"<<endl;
    return ;
    }
    int size=_word2Numbers[record]->size();

    if(size>1)
    {
        cout<<"word "<<word<<" occurs "<<size<<" times"<<endl;
    }
    else
    {
        cout<<"word "<<word<<" occurs "<<size<<" time"<<endl;
    }
    for(auto & i:*_word2Numbers[record])
    {
        cout<<"( line "<<i<<" ) "<<(*_lines)[i-1]<<endl;
    }
    cout<<"-------------------------------------"<<endl;
}
